// index.js
import * as echarts from '../../ec-canvas/echarts';
let chart = null;
function initChart(canvas, width, height, dpr) {
  const chart = echarts.init(canvas, null, {
    width: width,
    height: height,
    devicePixelRatio: dpr // 像素比
  });
  canvas.setChart(chart);

  var option = {
    responsive: {
      width: '100%' // 自适应屏幕宽度
    },
    title: {
      text: '温湿度折线图'
    },
    tooltip: {
      trigger: 'axis',
      confine:true
    },
    legend: {
      data: ['温度', '湿度'],
      right: '10%', // 或者 '0' 表示紧贴右侧
      top: '10%',   // 或者 '0' 表示紧贴顶部
      formatter: function (name) {
        // 自定义图例项的显示内容
        if (name === '温度') {
          return '温度 (°C)';
        } else if (name === '湿度') {
          return '湿度 (%)';
        }
        return name;
      }
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: ['2022-05-03\n10:30:59', '2022-05-03\n10:31:17', '2022-05-03\n10:31:35', '2022-05-03\n10:31:53'],
      axisLabel: {
        margin: 10, // 增加标签与轴之间的距离，以容纳多行文本
        interval: 0 // 显示所有标签
      }
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        margin: 13, // 增加标签与轴之间的距离，以容纳多行文本
        interval: 0 // 显示所有标签
      }
    },
    series: [
      // 温度数据
      {
        name: '温度',
        type: 'line',
        data: [23, 18, 29, 24],
        itemStyle: {
          color: '#337ab7'
        },
        label: {
          show: true,
          position: 'top',
          textStyle: {
            fontSize: 10
          }
        }
      },
      // 湿度数据
      {
        name: '湿度',
        type: 'line',
        data: [60, 40, 58, 45.5],
        itemStyle: {
          color: '#5cb85c'
        },
        label: {
          show: true,
          position: 'top',
          textStyle: {
            fontSize: 10,
          },
        }
      }
    ]
  };
  chart.setOption(option);
  return chart;
}
Page({
  data: {
    welcome:'晴天',
    location:'湖北省-宜昌市',
    weathertemperature:'22',
    currentWeather:{
      weatherIcon:'sun',
      temp:23,
      windDir:"西南风",
      humidity:45,
      precip:33
    },
    weatherForecast:[
      {
        date: '05-03',
        weatherIcon: 'sun', // 假设这是图标名称
        tempRange: '20~28'
      },
      {
        date: '05-04',
        weatherIcon: 'sun',
        tempRange: '20~28'
      },
      {
        date: '05-05',
        weatherIcon: 'sun',
        tempRange: '23~30'
      },
    ],
    deviceName:'ESP8266',
    temperature:35,
    humidity:23,
    soilMoisture:45,
    CO2Value:46,
    lightLux:56,
    precip:55,//降水量
    potNumber:1,
    ec:{
      onInit:initChart
    }
  },
  onLoad: function () {
    // 获取实时天气数据
    this.fetchWeatherNow();
    this.fetchThreeDayForecast();
    this.fetchDeviceName();
    const selectedPlantDisplayId = getApp().getGlobalData('selectedPlantDisplayId');
    if (selectedPlantDisplayId) {
      console.log('Selected Plant ID in another page:', selectedPlantDisplayId);
    }
    //获取表格数据
    // this.fetchChartData();
     // 设置定时器，每隔两秒获取数据
     const fetchDataInterval = setInterval(() => {
      this.fetchValue();
     }, 2000); // 每隔两秒执行一次

    // 保存定时器句柄
     this.setData({
       fetchDataInterval: fetchDataInterval
     });
    
  },
  onUnload: function () {
    //清除定时器
    clearInterval(this.data.fetchDataInterval);
  },
  onShow: function () {
    // const userInfo = wx.getStorageSync('userInfo');
    // if (!userInfo) {
    //   wx.navigateTo({
    //     url: '/pages/login/login',
    //   });
    // }
    // 获取实时天气数据
    this.fetchWeatherNow();
    // 获取三天天气数据
    // this.fetchThreeDayForecast();
     // 获取全局变量
    const selectedPlantId = getApp().getGlobalData('selectedPlantId');
    const selectedPlantDisplayId = getApp().getGlobalData('selectedPlantDisplayId');
    this.fetchDeviceName();
    setTimeout(() => {
      this.fetchValue();
    }, 500); // 等待0.5秒，以确保设备名已经被设置
     if (1) {
       this.setData({
         potNumber: selectedPlantDisplayId
       });
     }
  },
  onPullDownRefresh: function(){
    console.log("下拉刷新");
  },
  // 从后端获取数据,放到折线图显示
  // fetchChartData: function () {
  //   wx.request({
  //     url: 'http://localhost:8080/', // 替换为你的后端API地址
  //     method: 'GET',
  //     success: (res) => {
  //       if (res.statusCode === 200) {
  //         const { xAxisData, seriesData } = res.data; // 假设后端返回的数据格式
  //         this.setData({
  //           chartOption: {
  //             ...this.data.chartOption,
  //             xAxis: { data: xAxisData },
  //             series: [{ data: seriesData }]
  //           }
  //         });
  //         this.initChart();
  //       } else {
  //         wx.showToast({
  //           title: '获取数据失败',
  //           icon: 'none'
  //         });
  //       }
  //     },
  //     fail: (err) => {
  //       wx.showToast({
  //         title: '网络错误',
  //         icon: 'none'
  //       });
  //     }
  //   });
  // },
  fetchDeviceName:function(){
    const plantid = getApp().getGlobalData('selectedPlantId')==null?4:getApp().getGlobalData('selectedPlantId');
    wx.request({
      url: 'http://120.26.231.14:8080/device/getDeviceName/'+plantid,
      method: 'GET',
      header: {
        token: wx.getStorageSync('token')
      },
      success: (res) => {
        if (res.statusCode === 200 && res.data.code === '1') {
          const devicename=res.data.data;
          this.setData({
            deviceName:devicename,
          });
          console.log('获取设备名称:', devicename);
        } else {
          console.error('设备名称获取失败:', res.statusCode, devicename);
        }
      }
    })
  },
  fetchValue: function () {
    const name = 'ESP8266'; // 假设设备ID
    wx.request({
      url: 'http://120.26.231.14:8080/device/found/'+this.data.deviceName,
      method: 'GET',
      header: {
        token: wx.getStorageSync('token')
      },
      success: (res) => {
        if (res.statusCode === 200 && res.data.code === '1') {
          const data = res.data.data.body.data.list.propertyStatusInfo;
          const temperature = this.findPropertyValue(data, 'temperature');
          const environmentHumidity = this.findPropertyValue(data, 'EnvironmentHumidity');
          const co2value = this.findPropertyValue(data,'CO2Value');
          const soilmoisture = this.findPropertyValue(data,'SoilMoisture');
          const lightlux = this.findPropertyValue(data,'LightLux');
          this.setData({
            temperature: temperature ? parseFloat(temperature.value) : 0,
            humidity: environmentHumidity ? parseFloat(environmentHumidity.value) : 0,
            soilMoisture: soilmoisture ? parseFloat(soilmoisture.value) : 0,
            CO2Value: co2value ? parseFloat(co2value.value) : 0,
            lightLux: lightlux ? parseFloat(lightlux.value) : 0,
            // potNumber:
          });
          console.log("name:",this.data.deviceName);
          console.log('获取监测数据:', environmentHumidity, temperature);
        } else {
          console.error('监测数据获取失败:', res.statusCode, res.data);
        }
      },
      fail: (err) => {
        console.error('请求失败:', err);
      }
    });
  },
  findPropertyValue: function (propertyList, identifier) {
    for (let i = 0; i < propertyList.length; i++) {
      if (propertyList[i].identifier === identifier) {
        return propertyList[i];
      }
    }
    return null;
  },
  // 三天天气
  fetchThreeDayForecast: function () {
    wx.request({
      url: 'http://120.26.231.14:8080/weather',
      method: 'GET',
      header: {
        token: wx.getStorageSync('token')
      },
      success: (res) => {
        if (res.statusCode === 200) {
          const forecastData = res.data.daily;
          const processedForecast = forecastData.map(item => ({
            date: item.fxDate.substring(5), // 提取月份和日期部分
            weatherIcon: this.getWeatherIcon3(item.textDay),
            tempRange: `${item.tempMin}~${item.tempMax}`
          }));
          this.setData({
            weatherForecast: processedForecast,

          });
          console.log('三天天气预报:', forecastData);
        } else {
          console.error('三天天气预报获取失败:', res.statusCode, res.data);
        }
      },
      fail: (err) => {
        console.error('请求失败:', err);
      }
    });
  },
  getWeatherIcon3: function (textDay) {
    // 根据天气情况返回对应的图标名称
    if (textDay.includes('晴')) return 'clear-day';
    if (textDay.includes('雨')) return 'rain';
    if (textDay.includes('阴')) return 'cloudy';
    if (textDay.includes('多云')) return 'partly-cloudy-day';
    return 'unknown'; // 如果没有匹配的情况
  },
  fetchWeatherNow: function () {
    wx.request({
      url: 'http://120.26.231.14:8080/weatherNow',
      method: 'GET',
      header: {
        token: wx.getStorageSync('token')
      },
      success: (res) => {
        if (res.statusCode === 200) {
          console.log('Response:', res);
          const weatherData = res.data.now;
          const currentWeather = {
            weatherIcon: this.getWeatherIcon(weatherData.text),
            temp: weatherData.temp,
            windDir: weatherData.windDir,
            humidity: weatherData.humidity,
            precip: weatherData.precip
          };
          this.setData({
            welcome:weatherData.text,
            currentWeather: currentWeather,
          });
          console.log('实时天气预报:', weatherData);
        } else {
          console.error('获取实时天气数据失败:', res.statusCode, res.data);
        }
      },
      fail: (err) => {
        console.error('请求失败:', err);
      }
    });
  },
  getWeatherIcon: function (text) {
    // 根据天气情况返回对应的图标名称
    if (text.includes('晴')) return 'clear-day';
    if (text.includes('雨')) return 'rain';
    if (text.includes('阴')) return 'partly-cloudy-day';
    if (text.includes('多云')) return 'cloudy';
    return 'unknown'; // 如果没有匹配的情况
  },
  onChooseAvatar(e) {
    const { avatarUrl } = e.detail
    const { nickName } = this.data.userInfo
    this.setData({
      "userInfo.avatarUrl": avatarUrl,
      hasUserInfo: nickName && avatarUrl && avatarUrl !== defaultAvatarUrl,
    })
  },
  onInputChange(e) {
    const nickName = e.detail.value
    const { avatarUrl } = this.data.userInfo
    this.setData({
      "userInfo.nickName": nickName,
      hasUserInfo: nickName && avatarUrl && avatarUrl !== defaultAvatarUrl,
    })
  },
  getUserProfile(e) {

  },
  
})
